package avicit.bdp.dms.oauth2.handler;

import avicit.bdp.dms.oauth2.WebUtils;
import avicit.bdp.dms.oauth2.token.AccessToken;
import avicit.bdp.dms.oauth2.validator.AbstractClientDetailsValidator;
import avicit.bdp.dms.oauth2.validator.RefreshTokenClientDetailsValidator;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TODO
 *
 * @author xugb
 * @date 2024/4/12 14:45
 */

public class RefreshTokenHandler extends AbstractOAuthTokenHandler {
    private static final Logger LOG = LoggerFactory.getLogger(RefreshTokenHandler.class);

    public RefreshTokenHandler() {
    }

    public boolean support(OAuthTokenRequest tokenRequest) throws OAuthProblemException {
        String grantType = tokenRequest.getGrantType();
        return GrantType.REFRESH_TOKEN.toString().equalsIgnoreCase(grantType);
    }

    @Override
    public void handleAfterValidation() throws OAuthSystemException {
        String refreshToken = this.tokenRequest.getRefreshToken();
        AccessToken accessToken = this.oauthTokenService.changeAccessTokenByRefreshToken(refreshToken, this.tokenRequest.getClientId());
        OAuthResponse tokenResponse = this.createTokenResponse(accessToken);
        LOG.debug("'refresh_token' response: {}", tokenResponse);
        WebUtils.writeOAuthJsonResponse(this.response, tokenResponse);
    }

    @Override
    protected AbstractClientDetailsValidator getValidator() {
        return new RefreshTokenClientDetailsValidator(this.tokenRequest);
    }
}
